package com.zhoug.widget.popup;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;


import com.zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import com.zhoug.common.adapters.recycler.BaseViewHolder;
import com.zhoug.common.adapters.recycler.dividers.ListItemDecoration;
import com.zhoug.common.utils.AppUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.widget.R;

import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 列表popupWindow 文字
 */
public abstract class ListPopupManager<T> {
    private static final String TAG = "ListPopupManager";
    private Context context;
    private BasePopupWindow popupWindow;
    private RecyclerView recyclerView;
    private Adapter adapter;
    private View anchor;//锚点
    private List<T> data;
    private OnSelectListener onSelectListener;//选择监听

    private int selection=0;//当前选择
    private boolean changeSelectbg=true;//改变选中的背景

    /**list列表item的背景*/
    private @DrawableRes
    int itemBackground= R.drawable.widgets_list_popup_item_bg;
    /**list列表item选中的背景*/
    private @DrawableRes int itemSelectBackground=R.drawable.widgets_list_popup_item_select;

    private int itemPaddingTop=10;
    private int itemPaddingBottom=10;
    private int itemPaddingLeft=10;
    private int itemPaddingRight=10;



    public ListPopupManager(Context context) {
        this.context = context;
        init();

    }

    private void init(){
        popupWindow=new BasePopupWindow(context);
        View view= LayoutInflater.from(context).inflate(R.layout.widgets_layout_popup_list,null );
        recyclerView=view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new ListItemDecoration(context, OrientationHelper.VERTICAL));
        adapter=new Adapter();
        recyclerView.setAdapter(adapter);
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        //不能设置为null否则点击外部不能关闭,设置透明背景
        popupWindow.setTransparentBackground();
        popupWindow.setAnimationStyle(R.style.widgets_anim_window_popu_anchor_down);

    }

    /**
     * 如果窗口宽高为0则测量宽高
     */
    private void measureWindowSize(){
        if(popupWindow.getWidth()<=0 || popupWindow.getHeight()<=0){
            View contentView = popupWindow.getContentView();
            AppUtils.measureView(contentView);
            if(popupWindow.getWidth()<=0){
                popupWindow.setWidth(contentView.getMeasuredWidth());
            }
            if(popupWindow.getHeight()<=0){
                popupWindow.setHeight(contentView.getMeasuredHeight());
            }
        }
    }

    public void show(){
        //showAsDropDown 的对齐方式是v控件的左下角与popupWindow的控件左上角对齐
        //而popupWindow不会超出屏幕，所以显示效果是紧贴右边框。
        //小幅设置偏移量真实位置还是超出边框，窗口依旧会紧贴右边框，并不会看出有什么效果
        measureWindowSize();
        popupWindow.showAsDropDown(anchor);
          /* Disposable subscribe = Observable.timer(1, TimeUnit.SECONDS)
                .compose(SchedulersProvider.apply())
                .subscribe(i -> {
                    LogUtils.d(TAG, "show: i="+i);
                    int width = popupWindow.getWidth();
                    int height = popupWindow.getHeight();
                    LogUtils.d(TAG, "show: width="+width+",height="+height);



                }, throwable -> {
                    LogUtils.d(TAG, "show: "+throwable.getMessage());
                });*/
    }

    public void showAsDropDown(int gravity, int xoff, int yoff) {
        measureWindowSize();
        popupWindow.showAsDropDown(anchor,xoff,yoff,gravity);

    }

    /**
     * 显示在anchor的左边顶部对齐
     */
    public void showLeftAndTop() {
        measureWindowSize();
        int width = popupWindow.getWidth();
        LogUtils.d(TAG, "showLeft: width="+width);
        if(width>0){
            popupWindow.showAsDropDown(anchor,-width,-anchor.getHeight(), Gravity.TOP);
        }else{
            popupWindow.showAsDropDown(anchor);
        }



    }

    /**
     * 显示在整个屏幕的位置
     * @param gravity
     * @param x
     * @param y
     */
    public void showAtLocation(int gravity, int x, int y){
        //第一个参数是View类型的parent,虽然这里参数名是parent，其实，不是把PopupWindow放到这个parent里，
        // 并不要求这个parent是一个ViewGroup，这个参数名让人误解。官方文档
        // “a parent view to get the android.view.View.getWindowToken() token from
        //”,这个parent的作用应该是调用其getWindowToken()方法获取窗口的Token,所以，
        // 只要是该窗口(父类窗口)上的控件（例如：按钮控件）就可以了
        measureWindowSize();

        popupWindow.showAtLocation(anchor, gravity, x, y);
    }


    private class Adapter extends BaseRecyclerViewAdapter<T> implements View.OnClickListener{


        @Override
        public int getLayoutId(int viewType) {
            return R.layout.widgets_list_popup_item;
        }

        @NonNull
        @Override
        public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            BaseViewHolder vh = super.onCreateViewHolder(parent, viewType);
            vh.itemView.setPadding(itemPaddingLeft,itemPaddingTop ,itemPaddingRight ,itemPaddingBottom );
            vh.itemView.setBackgroundResource(itemBackground);

            return vh;
        }

        @Override
        public void onBindData(BaseViewHolder holder, T data, int position, int viewType) {
            if(data!=null){
                holder.setText(R.id.tv_text, getShowText(data));
                holder.itemView.setTag(position);
                holder.itemView.setOnClickListener(this);
                //选中的项背景
                if(changeSelectbg){
                    if(selection==position){
                        holder.itemView.setBackgroundResource(itemSelectBackground);
                    }else{
                        holder.itemView.setBackgroundResource(itemBackground);

                    }
                }

//                LogUtils.d(TAG, "onBindData: data="+data);
            }

        }



        @Override
        public void onClick(View v) {
            int position= (int) v.getTag();
            selection=position;
            if(changeSelectbg){
                notifyDataSetChanged();
            }
            if(onSelectListener!=null){
                popupWindow.dismiss();
                onSelectListener.onSelected(position);
            }

        }
    }
    public abstract String getShowText(T data);

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
        adapter.setData(data);
        adapter.notifyDataSetChanged();
    }

    public View getAnchor() {
        return anchor;
    }

    public void setAnchor(View anchor) {
        this.anchor = anchor;
    }

    public OnSelectListener getOnSelectListener() {
        return onSelectListener;
    }

    public void setOnSelectListener(OnSelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
    }

    public int getSelection() {
        return selection;
    }

    public void setSelection(int selection) {
        this.selection = selection;
    }

    public int getItemBackground() {
        return itemBackground;
    }

    public void setItemBackground(@DrawableRes int itemBackground) {
        this.itemBackground = itemBackground;
    }

    public int getItemSelectBackground() {
        return itemSelectBackground;
    }

    public void setItemSelectBackground(@DrawableRes int itemSelectBackground) {
        this.itemSelectBackground = itemSelectBackground;
    }

    public void setChangeSelectbg(boolean changeSelectbg) {
        this.changeSelectbg = changeSelectbg;
    }

    public void setItemPadding(int itemPaddingLeft, int itemPaddingTop, int itemPaddingRight, int itemPaddingBottom){
        this.itemPaddingLeft=itemPaddingLeft;
        this.itemPaddingTop=itemPaddingTop;
        this.itemPaddingRight=itemPaddingRight;
        this.itemPaddingBottom=itemPaddingBottom;
    }

    public PopupWindow getPopupWindow() {
        return popupWindow;
    }

    public interface OnSelectListener{
        void onSelected(int position);
    }
}
